package com.vanzo.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.vanzo.Tpplication;
import com.vanzo.encryption.ByteUtil;
import com.vanzo.encryption.Encryption;
import com.vanzo.encryption.R;
import com.vanzo.instruction.AT;
import com.vanzo.instruction.Instruction;
import com.vanzo.nfc.NFCManager;
import com.vanzo.util.LogFileUtil;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by tisen on 2018/3/5.
 */

public class StressTestActivity extends BaseActivity implements View.OnClickListener {

    private Instruction instruction;

    private TextView console;
    private ScrollView scrollView;
    private ImageView power;
    private ImageView control;
    private ImageView deleteLog;
    private boolean powerState;
    private boolean isTesting;
    private List<String> ats = new ArrayList<>();
    private int index = 0;
    NFCManager nfcMger;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stress_test);
        instruction = ((Tpplication) getApplication()).getInstruction();
        ats = Arrays.asList(getResources().getStringArray(R.array.stress_at));
        scrollView = (ScrollView) findViewById(R.id.stress_scr);
        console = (TextView) findViewById(R.id.stress_console);
        power = (ImageView) findViewById(R.id.stress_power_state);
        control = (ImageView) findViewById(R.id.stress_control);
        deleteLog = (ImageView) findViewById(R.id.stress_delete_log);
        LogFileUtil.setContext(this);
        nfcMger = new NFCManager(this);

        power.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!powerState) {
                    instruction.connect();
                } else {
                    instruction.disconnect();
                }
                powerState = !powerState;
                power.setImageResource(powerState ? R.mipmap.power_on : R.mipmap.power_off);
            }
        });
        instruction.setConsole(new Instruction.Console() {
            @Override
            public void onConsole(String result) {
                Message message = new Message();
                message.obj = result;
                consoleHandler.sendMessage(message);
            }
        });

        control.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isTesting) {
                    startTesting();
                } else {
                    stopTesting();
                }
                isTesting = !isTesting;
                control.setImageResource(isTesting ? R.mipmap.stop_stress : R.mipmap.start_stress);
            }
        });
        deleteLog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogFileUtil.delete();
            }
        });
        try {
            LogFileUtil.init();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    private Handler consoleHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String con = (String) msg.obj;
            if (con.startsWith("AT+")) {
                console.append("\r\n");
                console.append("\r\n send | " + con);
            } else {
                console.append("\r\n rece | " + con);
            }
            try {
                if (con.startsWith("AT+")) {
                    LogFileUtil.append(new StringBuffer(""));
                    LogFileUtil.append(new StringBuffer(" at send\t\t| " + (String) msg.obj));
                } else {
                    LogFileUtil.append(new StringBuffer(" at receiver\t\t| " + (String) msg.obj));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
//        instruction.start();
        powerState = instruction.isPower();
        power.setImageResource(powerState ? R.mipmap.power_on : R.mipmap.power_off);
        control.setImageResource(isTesting ? R.mipmap.stop_stress : R.mipmap.start_stress);
    }

    private final Timer timer = new Timer();
    private TimerTask task;
    private Handler taskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            instruction.sendInstruction("AT+" + ats.get(index));
            index++;
            index = index % ats.size();
        }
    };

    private void startTesting() {
        if (task == null) {
            task = new TimerTask() {
                @Override
                public void run() {
                    taskHandler.sendEmptyMessage(0);
                }
            };
        }
        timer.schedule(task, 2000, 2000);
    }

    private void stopTesting() {
        timer.cancel();
    }


    @Override
    protected void onPause() {
        super.onPause();
        try {
            LogFileUtil.save();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            nfcMger.verifyNFC();
        } catch (NFCManager.NFCNotSupported nfcnsup) {
            Toast.makeText(this, "nfc not supportecd", Toast.LENGTH_SHORT).show();
        } catch (NFCManager.NFCNotEnabled nfcnEn) {
            Toast.makeText(this, "nfc not enable", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
//        instruction.disconnect();
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Encryption.NFC binary = nfcMger.readBinaryFromTag(intent);
        if (binary != null) {
            console.append("\r\n binary = " + binary.toString());
            instruction.sendInstruction(AT.DMO_BINARY + "=" + ByteUtil.byteArrayToBit(binary.getBinary(), binary.getLength()));
        }
    }
}
